<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/07/27
 * Time: 下午5:13
 */
namespace App\Api\Controllers\Linkage;


use Illuminate\Support\Facades\Log;

class PayController extends BaseController
{
    //刷卡支付-用户被扫  -1 系统错误 0-其他 1-成功 2-验签失败 3-支付中 4-交易失败
    public function scan_pay($data){
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? 0;
            $txnAmt = $total_amount ? $total_amount*100 : 0;
            $authCode = $data['authCode'] ?? '';
            $goodsId = $data['goodsId'] ?? '';
            $goodsInfo = $data['goodsInfo'] ?? '';
            $backUrl = $data['backUrl'] ?? '';
            $merPriv = $data['merPriv'] ?? '';
            $faceFlag = $data['faceFlag'] ?? '';
            $ways_source = $data['ways_source'] ?? '';
            $ledgerAccountFlag = $data['ledgerAccountFlag'] ?? '';
            $goodsTag = $data['goodsTag'] ?? '';
            $subAppId = $data['subAppId'] ?? '';
            $longitude = $data['longitude'] ?? '';
            $latitude = $data['latitude'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $orderType = '';
            if ($ways_source == 'alipay') { //支付宝
                $orderType = 'alipay';
                $pay_platform_type = '1';
            } elseif ($ways_source == 'weixin') { //微信支付
                $orderType = 'wechat';
                $pay_platform_type = '2';
            } elseif ($ways_source == 'unionpay') { //银联二维码
                $orderType = 'unionpay';
                $pay_platform_type = '6';
            }
            $linkage_data = [
                'store_id' => $data['store_id'],
                'out_trade_no' => $out_trade_no,
                'subject' => '日用百货',
                'body' => '日用百货',
                'total_amount' => $txnAmt / 100,
                'subsidy_fee' => '0',
                'auth_code' => $authCode,
                'device_info' => mt_rand(10000000,99999999),
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                'share_order_type' => '0',
                'pay_platform_type' => $pay_platform_type, // 支付平台：1-支付宝；2-微信；6-云闪付；9-数字人民币 数字人民币该参数必填；
            ];
           
            $obj = new BaseController();
            $result = $obj->http_post(false, 'aggregation.barcode.pay', $linkage_data);
            $result = json_decode($result, true);
            
            if (isset($result['error_code'])) {
                if($result['error_code'] == '100'){
                    return [
                        'status' => '3',
                        'message' => '支付中',
                        'data' =>$result['return_value']
                    ];
                }else{
                    return [
                        'status' => '2',
                        'message' => '支付失败',
                        'data' =>$result['return_value']
                    ];
                }
            }else{
                if($result['return_value']['pay_status'] == '0'){
                    return [
                       'status' => '3',
                       'message' => '支付中',
                       'data' =>$result['return_value']
                   ];
                }else if($result['return_value']['pay_status'] == '1'){
                    return [
                       'status' => '1',
                       'message' => '支付成功',
                       'data' =>$result['return_value']
                   ];
                }else{
                    return [
                       'status' => '2',
                       'message' => '支付失败',
                       'data' =>$result['return_value']
                   ];
                }
            }
        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //公众号/小程序支付  -1 系统错误 0-其他 1-成功 2-验签失败 3-支付中 4-交易失败
    public function qr_submit($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $txnAmt = $total_amount ? ($total_amount * 100): '';
            $orderType = $data['orderType'] ?? '';
            $userId = $data['userId'] ?? '';
            $appId = $data['appId'] ?? '';
            $subAppId = $data['subAppId'] ?? '';
            $goodsInfo = $data['goodsInfo'] ?? '';
            $paymentValidTime = $data['paymentValidTime'] ?? '';
            $merPriv = $data['merPriv'] ?? '';
            $ledgerAccountFlag = $data['ledgerAccountFlag'] ?? '';
            $creditFlag = $data['creditFlag'] ?? '';
            $goodsTag = $data['goodsTag'] ?? '';
            $longitude = $data['longitude'] ?? '';
            $latitude = $data['latitude'] ?? '';
            $notify_url = $data['notify_url'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $linkage_data = [
                'orderTime' => date('YmdHis', time()), //订单时间，yyyyMMddHHmmss
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'orderNo' => $out_trade_no, //商户订单号
                'txnAmt' => $txnAmt, //交易金额，是人民币，且以分为单位
                'orderType' => $orderType, //订单类型,wechatJs:微信Js支付;alipayJs:支付宝Js支付;unionpayJs:银联云闪付js支付
                'userId' => $userId //用户标识,微信上传用户openid；支付宝上传用户buyer_id；银联二维码上传userAuthCode
            ];
            if ($appId) $linkage_data['appId'] = $appId; //C,APPID,微信及支付宝的AppId，如获取OpenID所使用的AppID非下单商户主体资质，则该字段无需上传
            if ($subAppId) $linkage_data['subAppId'] = $subAppId; //O，二级商户的appId
            if ($goodsInfo) $linkage_data['goodsInfo'] = $goodsInfo; //O，商品信息,可上送商品描述、商户订单号等信息，用户付款成功后会在微信账单页面展示
            if ($paymentValidTime) $linkage_data['paymentValidTime'] = $paymentValidTime; //O，订单有效时间(秒)，订单有效时间从调起用户密码键盘开始算起，超时之后,用户无法继续支付
            if ($notify_url) $linkage_data['backUrl'] = $notify_url; //O，结果通知地址. 必须以 http:// 开始
            if ($longitude) $linkage_data['longitude'] = $longitude; //O，商户交易所在位置经度，eg:-83.2345
            if ($latitude) $linkage_data['latitude'] = $latitude; //O，商户交易所在位置纬度，eg:-24.3094
            if ($merPriv) $linkage_data['merPriv'] = $merPriv; //O，商户私有域
            if ($ledgerAccountFlag) $linkage_data['ledgerAccountFlag'] = $ledgerAccountFlag; //O，分账标识，1：分账订单
            if ($creditFlag) $linkage_data['creditFlag'] = $creditFlag; //O，禁用信用卡标识，1：禁用信用卡
            if ($goodsTag) $linkage_data['goodsTag'] = $goodsTag; //O，商品标记（优惠券信息
//            Log::info('联动优势-公众号/小程序支付');
//            Log::info($linkage_data);
            $linkage_res = $this->http_post($this->url.$this->payUnifiedOrder, $linkage_data, $privateKey, $publicKey);
//            Log::info($linkage_res);
            if ($linkage_res['status'] == '1') {
                if ($linkage_res['data']['respCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => '交易成功',
                        'data' => $linkage_res['data']
                    ];
                } //交易支付中，调用查询确认
                elseif ($linkage_res['data']['respCode'] == '02') {
                    $orderQueryDate = [
                        'acqSpId' => $acqSpId,
                        'acqMerId' => $acqMerId,
                        'out_trade_no' => $out_trade_no,
                        'privateKey' => $privateKey,
                        'publicKey' => $publicKey
                    ];
                    $order_query = $this->order_query($orderQueryDate); //-1系统错误；0-其他；1-交易成功；2-验签失败；3-转入退款；4-交易结果未明；5-已关闭；6-已撤销(付款码支付)；7-明确支付失败
                    if ($order_query['status'] == '1') { //交易成功
                        return [
                            'status' => '3',
                            'message' => $order_query['message'] ?? '交易成功',
                            'data' => $order_query['data']
                        ];
                    } //交易失败
                    elseif ($order_query['status'] == '7') {
                        return [
                            'status' => '4',
                            'message' => $order_query['message'] ?? '交易失败',
                            'data' => $order_query['data']
                        ];
                    } //其他
                    else {
                        return [
                            'status' => '0',
                            'message' => $order_query['message'] ?? '交易未知',
                            'data' => $order_query['data']
                        ];
                    }

                } //其他
                else {
                    return [
                        'status' => '0',
                        'message' => $linkage_res['data']['respMsg']
                    ];
                }
            }
            elseif ($linkage_res['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败',
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-公众号/小程序支付-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //扫码支付-用户主扫  -1 系统错误 0-其他 1-成功 2-验签失败 3-支付中 4-交易失败
    public function qr_pay($data){
        try {
            // print_r($data);die;
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            // $txnAmt = $total_amount ? ($total_amount * 100): '';
            $txnAmt = $total_amount ? $total_amount: '';
            $ways_source = $data['ways_source'] ?? '';
            $goodsInfo = $data['goodsInfo'] ?? '';
            $paymentValidTime = $data['paymentValidTime'] ?? '';
            $merPriv = $data['merPriv'] ?? '';
            $longitude = $data['longitude'] ?? '';
            $latitude = $data['latitude'] ?? '';
            $notify_url = $data['notify_url'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $orderType = '';
            if ($ways_source == 'alipay') {
                $orderType = 'alipay'; //支付宝
                $pay_platform_type = '1';
            }
            elseif ($ways_source == 'weixin') {
                $orderType = 'weixin'; //微信支付
                $pay_platform_type = '2';
            }
            elseif ($ways_source == 'unionpay') {
                $orderType = 'unionpay'; //银联二维码
                $pay_platform_type = '6';
            }
            elseif ($ways_source == 'mobilepos') {
                $orderType = 'mobilepos'; //手机pos支付
            }
            elseif ($ways_source == 'dycode') {
                $orderType = 'dycode'; //动态立码付(支持当天交易)
            }

            $linkage_data = [
                // 'orderTime' => date('YmdHis', time()), //订单时间，yyyyMMddHHmmss
                // 'acqSpId' => $acqSpId, //代理商编号
                // 'acqMerId' => $acqMerId, //商户号
                // 'orderNo' => $out_trade_no, //商户订单号
                // 'txnAmt' => $txnAmt, //交易金额，是人民币，且以分为单位
                // 'orderType' => $orderType //订单类型
                
                'store_id' => $acqMerId, // 聚合收单平台为商户分配的惟一 ID,商户入驻后由平台返回
                'out_trade_no' => $out_trade_no, // 服务商订单号,64个字符以内。可包含字母、数字、下划线;需保证在接入的服务商系统中不重复
                'total_amount' => $txnAmt, // 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                'subsidy_fee' => 0, // 交易补贴金额，单位元 下游服务商给商户的交易补贴，若没有补贴业务，传0
                'pay_platform_type' => $pay_platform_type, // 支付平台：1-支付宝；2-微信；6-云闪付；9-数字人民币；13-银联全渠道分期；
                // 'order_type' => '3', // 订单类型：2-native，原生扫码支付（支持支付宝、银联二维码、数字人民币、银联全渠道分期）；3-JSAPI，公众号支付，服务窗支付；4-小程序支付；6-云闪付JS支付
                'subject' => '日用百货', // 订单标题。示例：Iphone 16G
                'body' => '日用百货', // 商品描述 商品或支付单简单描述，格式要求：门店品牌名- 城市分店名-实际商品名称 Eg:image-深圳腾大- QQ
                
                // 'pull_up_type' => '1', // 拉起支付方式 1- 调用微信支付宝官方接口方式；
                // 'user_id' => $data['userId'], // 微信公众号ID ；微信公众号支付的公众号id或微信小程序支付的小程序appid; 如果传了会使用此appid进行下单；没传会使用商户进件时最新配置的appid
                'notify_url' => $data['notify_url'], // 支付成功后回调地址，如果不填会用聚合收单平台默认的地址
            ];
            
            
            if ($ways_source == 'alipay') { //支付宝
                $linkage_data['order_type'] = '2';
            }
            elseif ($ways_source == 'weixin') { //微信支付
                $linkage_data['order_type'] = '3';
                $linkage_data['pull_up_type'] = '1';
                $linkage_data['user_id'] = $data['userId'];
            }
            elseif ($ways_source == 'unionpay') { //银联二维码
                $linkage_data['order_type'] = '2';
            }
            
            
            if ($goodsInfo) $linkage_data['goodsInfo'] = $goodsInfo; //O，商品信息
            if ($paymentValidTime) $linkage_data['paymentValidTime'] = $paymentValidTime; //O，订单有效时间(秒)，订单有效时间从调起用户密码键盘开始算起，超时之后,用户无法继续支付
            if ($notify_url) $linkage_data['backUrl'] = $notify_url; //O，结果通知地址. 必须以 http:// 开始
            if ($merPriv) $linkage_data['merPriv'] = $merPriv; //O，商户私有域
            if ($longitude) $linkage_data['longitude'] = $longitude; //O，商户交易所在位置经度，eg:-83.2345
            if ($latitude) $linkage_data['latitude'] = $latitude; //O，商户交易所在位置纬度，eg:-24.3094

            // print_r($linkage_data);die;
//            Log::info('联动优势-用户主扫-静态二维码');
//            Log::info($linkage_data);
            // $linkage_res = $this->http_post($this->url.$this->payQrpay, $linkage_data, $privateKey, $publicKey);
            
            $obj = new BaseController();
            $result = $obj->http_post(false, 'aggregation.prepay', $linkage_data);
            $result = json_decode($result, true);
            
            if ($result['success'] == 'true') {
                if($ways_source=='weixin'){
                    if (isset($result['return_value']['mini_pay_info'])) {
                        return [
                            'status' => '1',
                            'message' => '交易成功',
                            'data' => $result['return_value']
                        ];
                    }
                    else {
                        return [
                            'status' => '0',
                            'message' => '交易失败'
                        ];
                    }
                }else{
                    if (isset($result['return_value']['qr_code'])) {
                        return [
                            'status' => '1',
                            'message' => '交易成功',
                            'data' => $result['return_value']
                        ];
                    }
                    else {
                        return [
                            'status' => '0',
                            'message' => '交易失败'
                        ];
                    }
                }
            }else {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }
        } catch (\Exception $ex) {
            Log::info('扫码支付-用户主扫-静态二维码-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //查询订单 -1系统错误；0-其他；1-交易成功；2-验签失败；3-转入退款；4-交易结果未明；5-已关闭；6-已撤销(付款码支付)；7-明确支付失败
    public function order_query($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $trade_no = $data['trade_no'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'out_trade_no' => $out_trade_no //商户订单号
            ];
            if ($trade_no) $linkage_data['transactionId'] = $trade_no; //O，联动优势的订单号，建议优先使用
            $re = $obj->http_post(false, 'aggregation.pay.query', $linkage_data);
            $re = json_decode($re, true);
            if (isset($re['return_value']['error_code'])) {
                if($re['return_value']['error_code'] == '100'){
                    return [
                        'status' => '1',
                        'pay_status' => '2',
                        'message' => '支付中',
                        'data' =>$re['return_value']
                    ];
                }else{
                    return [
                        'status' => '1',
                        'pay_status' => '3',
                        'message' => '支付失败',
                        'data' =>$re['return_value']
                    ];
                }
            }else{
                
                 if($re['return_value']['pay_status'] == '0'){
                    //  print_r(2);die;
                     return [
                        'status' => '1',
                        'message' => '支付中',
                        'pay_status' => '2',
                        'data' =>$re['return_value']
                    ];
                 }else if($re['return_value']['pay_status'] == '1'){
                     return [
                        'status' => '1',
                        'pay_status' => '1',
                        'message' => '支付成功',
                        'data' =>$re['return_value']
                    ];
                 }else{
                     return [
                        'status' => '1',
                        'pay_status' => '3',
                        'message' => '支付失败',
                        'data' =>$re['return_value']
                    ];
                 }
            }
        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => '支付失败'
            ];
        }
    }


    //交易撤销 -1系统错误；0-其他；1-处理成功；2-验签失败
    public function order_revoke($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'orderNo' => $out_trade_no //商户订单号
            ];
//            Log::info('联动优势-交易撤销');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payCancelOrder, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                //除了成功（00）的返回码需要做对应的逻辑处理，其他返回码均不需要做处理
                if ($re['data'] ['respCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $re['data']['respMsg'] ?? '处理成功',
                        'data' => $re['data']
                    ];
                } else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg'] ?? '处理未知',
                        'data' => $re['data']
                    ];
                }
            } elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            } else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

        } catch (\Exception $ex) {
            Log::info('联动优势-交易撤销-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款（支持部分退款，支持对90天以内的成功订单） -1系统错误；0-其他；1-成功；2-验签失败；3-失败
    public function refund($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $out_refund_no = $data['out_refund_no'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'out_trade_no' => $out_trade_no, //
                'out_refund_no' => $out_refund_no,
            ];
            
            $re = $obj->http_post(false, 'aggregation.pay.refund', $linkage_data);
            
            $re = json_decode($re, true);
            file_put_contents('liandong.log',var_export($re,true)."\r\n",FILE_APPEND);

            if ($re['return_value']['refund_status'] == 'REFUND_SUCCESS' || $re['return_value']['refund_status'] == 'REFUND_PROCESSING') {
                return [
                    'status' => '1',
                    'message' => '退款受理成功',
                    'data' => $re['return_value']
                ];
            }
            else {
                return [
                    'status' => '2',
                    'message' => '退款失败'
                ];
            }

        } catch (\Exception $ex) {
            Log::info('联动优势-退款-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询  -1系统错误；0-其他；1-成功；2-验签失败；3-失败；4-处理中
    public function refund_query($data)
    {
        try {
            $acqSpId = $data['acqSpId'];
            $acqMerId = $data['acqMerId'] ?? '';
            $refund_no = $data['refund_no'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'refund_no' => $refund_no //退款流水号，本次退货交易的订单号
            ];
//            Log::info('联动优势-退款查询');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payRefundQuery, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    if ($re['data']['origRespCode'] == '00') {
                        return [
                            'status' => '1',
                            'message' => $re['data']['respMsg'] ?? '退款成功',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['origRespCode'] == '01') {
                        return [
                            'status' => '3',
                            'message' => $re['data']['respMsg'] ?? '退款失败',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['origRespCode'] == '02') {
                        return [
                            'status' => '4',
                            'message' => $re['data']['respMsg'] ?? '退款处理中',
                            'data' => $re['data']
                        ];
                    }
                } else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg'] ?? '退款状态未知',
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-退款查询-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //关闭订单（支付中/支付失败 调用） -1系统错误；0-其他；1-交易成功；2-验签失败
    public function order_close($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId,
                'acqMerId' => $acqMerId,
                'orderNo' => $out_trade_no //订单号
            ];
//            Log::info('联动优势-关闭订单');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payCloseOrder, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $re['data']['respMsg'] ?? '交易关闭成功',
                        'data' => $re['data']
                    ];
                } else {
                    return [
                        'status' => '3',
                        'message' => $re['data']['respMsg'] ?? '交易关闭失败',
                        'data' => $re['data']
                    ];
                }
            } elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

        } catch (\Exception $ex) {
            Log::info('联动优势-关闭订单-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //获取微信刷脸调用凭证 -1系统错误 0-其他 1-成功 2-验签失败
    public function wx_face_voucher($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $rawDate = $data['raw_data'] ?? '';
            $appid = $data['appid'] ?? '';
            $mchId = $data['mchId'] ?? '';
            $subMchId = $data['subMchId'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'rawDate' => $rawDate //初始数据
            ];
            if ($appid) $linkage_data['appid'] = $appid; //O，商户号绑定的公众号/小程序appid
            if ($mchId) $linkage_data['mchId'] = $mchId; //O，微信商户号
            if ($subMchId) $linkage_data['subMchId'] = $subMchId; //O，微信子商户号(服务商模式)

//            Log::info('联动优势-获取微信刷脸调用凭证');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payWxface, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    //除了成功（00）的返回码需要做对应的逻辑处理，其他返回码均不需要做处理
                    return [
                        'status' => '1',
                        'message' => '处理成功',
                        'data' => $re['data']
                    ];
                }
                else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg']
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-获取微信刷脸凭证-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //查询D0结算结果 -1系统错误 0-其他 1-处理成功 2-验签失败 3-结算处理中,稍后查询 4-结算失败
    public function query_settle($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $trade_no = $data['trade_no'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'orderNo' => $out_trade_no //商户订单号
            ];
            if ($trade_no) $linkage_data['transactionId'] = $trade_no; //O，联动优势的订单号，建议优先使用
//            Log::info('联动优势-查询D0结算结果');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payWxface, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    //除了成功（00）的返回码需要做对应的逻辑处理，其他返回码均不需要做处理；返回码为成功（00），根据结算结果settleRes判断结算是否成功
                    if ($re['data']['settleRes'] == '00') { //00--结算成功
                        return [
                            'status' => '1',
                            'message' => $re['data']['respMsg'] ?? '处理成功',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['settleRes'] == '00') { //02--结算处理中，稍后查询
                        return [
                            'status' => '3',
                            'message' => $re['data']['respMsg'] ?? '结算处理中，稍后查询',
                            'data' => $re['data']
                        ];
                    }
                    else { //其他结算失败
                        return [
                            'status' => '4',
                            'message' => $re['data']['respMsg'] ?? '结算失败',
                            'data' => $re['data']
                        ];
                    }
                }
                else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg']
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-查询D0结算结果-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //查询t1/d1结算结果 -1系统错误 0-其他 1-支付成功 2-验签失败 3-其他情况
    public function query_t1_settle($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'settleDate' => date('Ymd', time()) //结算日期，格式yyyyMMdd
            ];
//            Log::info('联动优势-查询t1/d1结算结果');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payQueryT1Settle, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    //除了成功（00）的返回码需要做对应的逻辑处理，其他返回码均不需要做处理；返回码为成功（00），根据结算结果settleRes判断结算是否成功
                    if (isset($re['data']['settleList'])) {
                        $resultList = json_decode($re['data']['settleList'], true);
                        $settleState = $resultList['settleState']; //结算状态

                        switch ($settleState) {
                            case '00':  $message = '支付成功';  break;
                            case '01':  $message = '支付失败';  break;
                            case '02':  $message = '处理中';  break;
                            case '03':  $message = '退款中';  break;
                            case '04':  $message = '交易撤销';  break;
                            case '05':  $message = '待确认';  break;
                            case '06':  $message = '已冻结';  break;
                            case '07':  $message = '待解冻';  break;
                            case '08':  $message = '交易失败退款中';  break;
                            case '09':  $message = '交易失败退单成功';  break;
                            case '10':  $message = '余额不足';  break;
                            case '11':  $message = '付款防重已拦截';  break;
                            case '99':  $message = '未知状态';  break;
                            default:  $message = '未知状态';
                        }

                        if ($settleState == '00') {
                            return [
                                'status' => '1',
                                'message' => $message,
                                'data' => $resultList
                            ];
                        }
                        else {
                            return [
                                'status' => '3',
                                'message' => $message,
                                'data' => $resultList
                            ];
                        }
                    }
                }
                else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg']
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-查询D0结算结果-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //商户资质上传 -1系统错误 0-其他 1-上传成功 2-验签失败 3-上传失败
    public function upload_qualification($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $merId = $data['merId'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'merId' => $merId, //报备编号，商户基本信息开户成功返回的商户报备编号
                'imageType' => '', //资质图片类型，个体--idCardFront，法人身份证正面，必传；idCardBack，法人身份证反面，必传；bankCardPhotoFront，银行卡正面，settleAccountType=2、3时必传；bankCardPhotoBack，银行卡反面，settleAccountType=2、3时必传，openingLicenseAccountPhoto，开户证明文件，settleAccountType=1时必传；acquiringAgreementPhoto，商户收单协议照片，signType=0(纸质协议)时必传；signAuthLetterPhoto，签约授权书，signType=1(电子协议)时必传；businessLicensePhoto，营业执照照片，必传；taxImg，税务登记证，三证合一不传，非三证合一必传；organizationImg	组织机构代码证，三证合一不传，非三证合一必传；storeHeadPhoto，门店门头照，必传；storeHallPhoto，门店内景照，必传；storeCashierPhoto，门店收银台照，必传；settleAuthLetterPhoto	结算授权函，settleAccountType=3时必传；settleAuthIdcardfront，结算授权人身份证正面，settleAccountType=3时必传；settleAuthIdCardBack，结算授权人身份证反面，settleAccountType=3时必传；
                //企业--idCardFront	法人身份证正面	必传；idCardBack	法人身份证反面	必传；bankCardPhotoFront	银行卡正面	settleAccountType=2时必传；bankCardPhotoBack	银行卡反面	settleAccountType=2时必传；openingLicenseAccountPhoto	开户证明文件	settleAccountType=1时必传；acquiringAgreementPhoto	商户收单协议照片	signType=0(纸质协议)时必传；signAuthLetterPhoto	签约授权书	signType=1(电子协议)时必传；businessLicensePhoto	营业执照照片	必传；taxImg	税务登记证	三证合一不传，非三证合一必传；organizationImg	组织机构代码证	三证合一不传，非三证合一必传；storeHeadPhoto	门店门头照	必传；storeHallPhoto	门店内景照	必传；storeCashierPhoto	门店收银台照	必传；settleAuthLetterPhoto	结算授权函	settleAccountType=2时必传；settleAuthIdcardfront	结算授权人身份证正面	settleAccountType=2时必传；settleAuthIdCardBack	结算授权人身份证反面	settleAccountType=2时必传
                //小微--idCardFront	法人身份证正面	必传；idCardBack	法人身份证反面	必传；bankCardPhotoFront	银行卡正面	必传；bankCardPhotoBack	银行卡反面	必传；storeHeadPhoto	门店门头照	必传；storeHallPhoto	门店内景照	必传；storeCashierPhoto	门店收银台照	必传；acquiringAgreementPhoto	商户收单协议照片	signType=0(纸质协议)时必传
                'imageSource' => '', //上传资质图片，图片转成字节流之后采用base64编码为字符串，作为此项值传输至服务端。读取文件至byte流里面，并使用base64编码，将其作为本字段value值
                'imageName' => '', //上传资质的名称，商户可自行定义
            ]; //请不要最后上传商户收单协议照片，最后上传收单协议照片，只能上传一张不能上传多张，请注意
//            Log::info('联动优势-商户资质上传');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->uploadQualification, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $re['data']['respMsg'] ?? '上传成功',
                        'data' => $re['data']
                    ];
                }
                else {
                    return [
                        'status' => '3',
                        'message' => $re['data']['respMsg'] ?? '上传失败',
                        'data' => $re['data']
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-商户资质上传-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //商户信息查询 -1系统错误 0-其他 1-已完成 2-验签失败 3-初始（资料待完善） 4-待审核 5-审核失败（已驳回） 6-修改待审核 7-修改审核驳回 8-待签约 9-修改资质待上传
    public function query_merchant_info($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $merId = $data['merId'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //C,商户号，merId和acqMerId必须存在一个
//                'merId' => $merId //C,报备编号，merId和acqMerId必须存在一个
            ];
//            Log::info('联动优势-商户信息查询');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->merchantsQueryMerchantInfo, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    //审核状态
                    if ($re['data']['auditStatus'] == '2') {
                        return [
                            'status' => '1',
                            'message' => $re['data']['auditMsg'] ?? '已完成',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '0') {
                        return [
                            'status' => '3',
                            'message' => $re['data']['auditMsg'] ?? '初始（资料待完善）',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '1') {
                        return [
                            'status' => '4',
                            'message' => $re['data']['auditMsg'] ?? '待审核',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '1') {
                        return [
                            'status' => '5',
                            'message' => $re['data']['auditMsg'] ?? '审核失败（已驳回）',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '1') {
                        return [
                            'status' => '6',
                            'message' => $re['data']['auditMsg'] ?? '修改待审核',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '1') {
                        return [
                            'status' => '7',
                            'message' => $re['data']['auditMsg'] ?? '修改审核驳回',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '1') {
                        return [
                            'status' => '8',
                            'message' => $re['data']['auditMsg'] ?? '待签约',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['auditStatus'] == '1') {
                        return [
                            'status' => '9',
                            'message' => $re['data']['auditMsg'] ?? '修改资质待上传',
                            'data' => $re['data']
                        ];
                    }

                }
                else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg'],
                        'data' => $re['data']
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-商户信息查询-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //微信参数配置-支付授权目录 -1系统错误 0-其他 1-成功 2-验签失败 3-失败
    public function merchantsJsApiPath($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $jsapiPath = $data['jsapiPath'] ?? '';
            $publicKey = $data['publicKey'] ?? '';
            $privateKey = $data['privateKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'jsapiPath' => $jsapiPath //支付授权目录
            ];
//            Log::info('联动优势-微信参数配置-支付授权目录');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->merchantsJsApiPath, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $re['data']['respMsg'] ?? '授权成功',
                        'data' => $re['data']
                    ];
                } else {
                    return [
                        'status' => '3',
                        'message' => $re['data']['respMsg'] ?? '授权失败',
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-微信参数配置-支付授权目录-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //微信参数配置-子商户appId -1系统错误 0-其他 1-成功 2-验签失败 3-失败
    public function merchantsSubAppid($data)
    {
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $subAppid = $data['subAppid'] ?? '';
            $publicKey = $data['publicKey'] ?? '';
            $privateKey = $data['privateKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'subAppid' => $subAppid //子商户SubAPPID
            ];
//            Log::info('联动优势-微信参数配置-子商户appId');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->merchantsSubAppid, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $re['data']['respMsg'] ?? '成功',
                        'data' => $re['data']
                    ];
                } else {
                    return [
                        'status' => '3',
                        'message' => $re['data']['respMsg'] ?? '失败',
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-微信参数配置,子商户appId-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


}
